package cn.lsoft.undoner.service.impl;

import cn.lsoft.undoner.service.MailSendService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.util.ArrayList;

import static org.apache.log4j.Logger.getLogger;

/**
 * Created by ${<A HREF="mailto:undoner@gmail.com">undoner</A>} on 16-12-20.
 */
@Service
public class MailSendServiceImpl implements MailSendService {
    private static final Logger LOGGER = getLogger(MailSendServiceImpl.class);
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Value("${mail.username}")
    private String from;

    @Value("${mail.mq.size.alert.to}")
    private String toMqSizeAlertStr;
    @Value("${mail.mq.size.alert.cc}")
    private String ccMqSizeAlertStr;

    private InternetAddress[] toMqSizeAlertAddress;
    private InternetAddress[] ccMqSizeAlertAddress;


    @PostConstruct
    public void init() {
        toMqSizeAlertAddress = initAddress(toMqSizeAlertStr);
        ccMqSizeAlertAddress = initAddress(ccMqSizeAlertStr);
    }

    /**
     * 初始化邮件地址信息
     * @param
     * @return
     * @throws Exception
     */
    private InternetAddress[] initAddress(String addressStr){
        InternetAddress[] resultAddressArray;
        ArrayList<InternetAddress> internetAddresses = new ArrayList<InternetAddress>();
        for (String cc : addressStr.split(",")) {
            if (StringUtils.isNotEmpty(cc)) {
                try {
                    internetAddresses.add(new InternetAddress(cc));
                } catch (AddressException e) {
                    LOGGER.warn("fail to decode " + cc, e);
                }
            }
        }
        resultAddressArray = internetAddresses.toArray(new InternetAddress[internetAddresses.size()]);
        return resultAddressArray;
    }

    /**
     * 发送mq报警邮件
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public void sendMailMqAlertMsg(String queueName, Long queueSize)  throws Exception{
        String subject = "[Urgent][MQ] MQ Message Alert!";
        String context = queueName + "有任务堆积，请及时处理并查明原因!<br/><br/><br/>";
        InternetAddress[] toMqSizeAlertArray =this.toMqSizeAlertAddress;
        InternetAddress[] ccMqSizeAlertArray=this.ccMqSizeAlertAddress;
        sendMail(subject, context,toMqSizeAlertArray,ccMqSizeAlertArray);
        LOGGER.debug( "sendMailMqAlertMsg: "+context);
    }

    /**
     * 发送邮件通用方法
     * @param
     * @return
     * @throws Exception
     */
    private void sendMail(String subject, String body,InternetAddress[] toArray ,InternetAddress[] ccArray) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, toArray);
        mimeMessage.setRecipients(Message.RecipientType.CC, ccArray);
        mimeMessage.setSubject(subject, "utf-8");
        mimeMessage.setContent(body, "text/html;charset = utf-8");

        mailSender.send(mimeMessage);
    }
}
